/**
 * crossframe_rpc_t handle the transmission and reception of
 * message between frames (even on different domains)
*/
var crossframe_rpc_t = function(){
	/**
	 * Send a message to a iframe_dst
	 * 
	 * @param proxy_uri {string} uri of the proxy document
	 * @param iframe_dst {string} the reference of destination frame. e.g "parent.frames['foo']"
	 * @param message {string} the message to send (if you need a non string object, do the json convertion)
	*/
	var send	= function(proxy_uri, iframe_dst, message){
		// Create a new hidden iframe.
		var el = document.createElement("iframe");
		el.style.visibility	= "hidden";
		el.style.position	= "absolute";
		el.style.top 		= el.style.left		= "0";
		el.style.width		= el.style.height	= "0";

		// Listen for the onload event.
		el.addEventListener('load', function (){
			console.info('msg iframe loaded. will be deleted in a sec');
			// first, remove the event listener or the iframe
			// we intend to discard will not be freed...
			el.removeEventListener("load", arguments.callee, false);
			// discard the iframe... after 1sec
			// - i dislike this timer a lot
			setTimeout(function (){
				console.info('msg iframe deleted');
				document.body.removeChild(el);
			}, 1000);
		}, false);
		
		// Compose the message...
		var hash_str	= "iframe_dst="		+ escape(iframe_dst)	+
					"&message="	+ escape(message)	+
					"&domain="	+ escape(document.domain) +
					"&uri="		+ escape(location.href);
		// Set its src first...
		el.src = proxy_uri + "#" + hash_str;
		// happen it to the body
		document.body.appendChild(el);
	}

	/**
	 * Define a generic custom_event_t
	 * - it is used to fire/subscribe event
	 * - see credit on http://www.geekdaily.net/2008/04/02/javascript-defining-and-using-custom-events/
	*/
	var custom_event_t = function() {
		//name of the event
		this.eventName	= arguments[0];
		var mEventName	= this.eventName;
	
		//function to call on event fire
		var eventAction	= null;
	
		//subscribe a function to the event
		this.subscribe	= function(fct) {
			eventAction	= fct;
		};
	
		//fire the event
		this.fire	= function(domain, uri, message){
			this.eventName	= mEventName;
			if( eventAction != null ){
				eventAction(domain, uri, message);
			}else{
				// TODO this stuff should be removed
				alert('There was no function subscribed to the ' + mEventName + ' event!');
			}
		};
	};
	// instanciation of the custom event
	var event	= new custom_event_t("onCrossframeMessage");

	// return public functions and variables
	return {
		send:	send,
		event:	event
	};
}

// create an instance of crossframe_rpc_t
// - needed as it is used by the proxy to notify event
var crossframe_rpc	= new crossframe_rpc_t();
